package com.huaxin.hxcloud.main;

import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.IBinder;
import android.os.SystemClock;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.mapapi.model.LatLng;
import com.huaxin.common.AppManager;
import com.huaxin.common.BaseActivity;
import com.huaxin.common.BaseApp;
import com.huaxin.common.Constants;
import com.huaxin.common.Entity.BaseDTO;
import com.huaxin.common.Entity.HxScAppVersionDTO;
import com.huaxin.common.Entity.UserInfoDTo;
import com.huaxin.common.Global;
import com.huaxin.common.tools.HxTransmitRequestHelper;
import com.huaxin.common.tools.RequestHelper;
import com.huaxin.common.tts.Constant;
import com.huaxin.common.utils.DialogUtil;
import com.huaxin.common.utils.HxAppClearMgr;
import com.huaxin.common.utils.HxUtils;
import com.huaxin.common.utils.PrefUtil;
import com.huaxin.common.utils.StringUtils;
import com.huaxin.common.utils.ToastUtil;
import com.huaxin.common.utils.Util;
import com.huaxin.common.view.MyFragmentTabHost;
import com.huaxin.hxcloud.R;
import com.huaxin.hxcloud.activity.MainTab;
import com.huaxin.hxcloud.find.view.InfoPagerFragment;
import com.huaxin.hxcloud.fragment.MyPagerFragment;
import com.huaxin.hxcloud.fragment.PromotionFragment;
import com.huaxin.hxcloud.fragment.WorkPagerFragment;
import com.huaxindata.im.main.chathistory.MessageFragment;
import com.huaxindata.im.main.manager.ContactManager;
import com.huaxindata.im.main.manager.HistoryContactManager;
import com.huaxindata.im.main.manager.UserManager;
import com.huaxindata.im.model.contact.Contact;
import com.huaxindata.im.model.contact.ContactGroup;
import com.huaxindata.im.model.contact.ContactPerson;
import com.huaxindata.im.model.db.ContactStore;
import com.huaxindata.im.model.entity.ChatMessage;
import com.huaxindata.im.model.entity.ChatMessageBody;
import com.huaxindata.im.model.entity.ChatSysMessageBody;
import com.huaxindata.im.service.MessageService;
import com.huaxindata.im.service.OnMessageReceiveListener;
import com.server.HxScUpdataService;

import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindArray;
import butterknife.BindString;
import butterknife.BindView;
import cn.jpush.android.api.JPushInterface;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import static com.baidu.mapapi.BMapManager.getContext;


/**
 * Created by Administrator on 2016/9/6.
 */
public class HomeActivity extends BaseActivity implements TabHost.OnTabChangeListener,
        MyPagerFragment.ProfileFragmentCallback,
        MessageService.ConnectionLostListener {

    private final FragmentManager mFragmentManager = getSupportFragmentManager();
    private MessageFragment   mMessageFragment;
    private WorkPagerFragment mWorkPagerFragment;

    @BindView(R.id.vRealTabContent)
    FrameLayout       vRealTabContent;
    @BindView(R.id.vTabHost)
    MyFragmentTabHost vTabHost;


    @BindString(R.string.main_tab_name_news)
    String mTitle;

    @BindArray(R.array.main_titles_arrays)
    String mTitles[];

    TextView msgCountTv;

    @BindView(R.id.vWork)
    ImageView vWork;
    private long mBackPressedTime;
    private static final String  TAG    = "HomeActivity";
    public static        boolean status = false;

    private MessageService mMessageService;//接收消息的service的对象实例
    private boolean        mIsBind;
    private AlertDialog    mSecureDialog;

    protected int getContentViewId() {
        return R.layout.activity_home;
    }

    @Override
    public void requestData() {
        //在fragment中更新此处不需要请求
        // userInfo();
    }

    @Override
    public void initData() {
        //获取联系人数据 放到子线程中
        ContactManager.initData();
        if (Constant.SCOrgcodeFirst.equals(UserManager.getFirstOrgCode())) {
            upDateVersion(HxUtils.getVersionName(this), 0);
        }
    }

    /**
     * 更新版本
     *
     * @param version
     * @param type    1=IOS 0=android
     */
    public void upDateVersion(final String version, int type) {
        Call<HxScAppVersionDTO> call = HxTransmitRequestHelper.getRequestApi().SccheckUpdate(version, type);
        autoClose(call);
        call.enqueue(new Callback<HxScAppVersionDTO>() {
            @Override
            public void onResponse(Call<HxScAppVersionDTO> call, Response<HxScAppVersionDTO> response) {
                HxScAppVersionDTO versionDTO = response.body();
                if (response.isSuccessful() && versionDTO != null) {
                    if (versionDTO.isNeedUpdate()) {
                        showUpdataDialog(HomeActivity.this,
                                UserManager.getServerAddress() + versionDTO.getUrl(), version, versionDTO.getNewVersion());
                    }
                }
            }

            @Override
            public void onFailure(Call<HxScAppVersionDTO> call, Throwable t) {

            }
        });

    }

    /**
     * 打开提示下载Dialog
     *
     * @param context
     * @param url
     * @param version
     */
    private void showUpdataDialog(final Context context, final String url, String oldversion, String version) {
        AlertDialog.Builder dialog = DialogUtil.getDialog(context);
        dialog.setTitle("发现新版本");
        dialog.setMessage("当前版本为" + oldversion + ",新版本为" + version + ",请更新以获取更多功能。");
        dialog.setPositiveButton("确定更新", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                dialogInterface.dismiss();
                if (!HxUtils.isWifi(context)) {
                    DialogUtil.getConfirmDialog(context, "请在wifi环境下更新", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            openDownloadService(url);
                            ToastUtil.showToast("APP更新下载中...");
                        }
                    }).show();
                } else {
                    openDownloadService(url);
                    ToastUtil.showToast("APP更新下载中...");
                }
            }
        });
        dialog.setNegativeButton("取消", null);
        dialog.show();

        //        DialogUtil.getConfirmDialog(context, "当前版本为" + oldversion+ ",新版本为"+version+",请更新以获取更多功能。", new DialogInterface.OnClickListener() {
        //            @Override
        //            public void onClick(DialogInterface dialog, int which) {
        //                if (!HxUtils.isWifi(context)) {
        //                    dialog.dismiss();
        //                    DialogUtil.getConfirmDialog(context, "请在wifi环境下更新", new DialogInterface.OnClickListener() {
        //                        @Override
        //                        public void onClick(DialogInterface dialog, int which) {
        //                            openDownloadService(url);
        //                        }
        //                    }).show();
        //                } else {
        //                    openDownloadService(url);
        //                }
        //
        //            }
        //        }).show();
    }

    /**
     * 开启下载服务
     *
     * @param downUrl
     */
    public void openDownloadService(String downUrl) {
        Intent intent = new Intent(this, HxScUpdataService.class);
        intent.putExtra("downLoadUrl", downUrl);
        startService(intent);
    }


    @Override
    public void initView() {
        HistoryContactManager.init(this);//初始化历史记录联系人数据库
        //TODO 绑定聊天服务
        bindToService();
        JPushInterface.requestPermission(this);
        vTabHost.setup(this, mFragmentManager, R.id.vRealTabContent);
        vTabHost.getTabWidget().setDividerDrawable(null);
        initTabs();
        vTabHost.setOnTabChangedListener(this);
        vTabHost.setCurrentTab(2);
        //2秒传一次经纬度,跟踪工单的进度
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            public void run() {
                requestAddress(BaseApp.getLatLng());
            }
        }, 2000);
        int notifi = PrefUtil.get(Global.getUser().getUserId() + Constants.notification_note, 0);
        if (notifi == 1) {
            return;
        }
        //判断用户是否开启通知权限
        if (!Util.isNotificationEnabled(this)) {
            AlertDialog notificationDialog = new AlertDialog.Builder(this)
                    .setTitle("友情提示").setMessage(R.string.notification)
                    .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            PrefUtil.set(Global.getUser().getUserId() + Constants.notification_note, 1);
                        }
                    }).setPositiveButton("设置", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            //跳转设置界面
                            Intent localIntent = new Intent();
                            localIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            if (Build.VERSION.SDK_INT >= 9) {
                                localIntent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
                                localIntent.setData(Uri.fromParts("package", getPackageName(), null));
                            } else if (Build.VERSION.SDK_INT <= 8) {
                                localIntent.setAction(Intent.ACTION_VIEW);
                                localIntent.setClassName("com.android.settings", "com.android.setting.InstalledAppDetails");
                                localIntent.putExtra("com.android.settings.ApplicationPkgName", getPackageName());
                            }
                            startActivity(localIntent);
                        }
                    })
                    .setCancelable(false)
                    .create();
            notificationDialog.setCanceledOnTouchOutside(true);
            notificationDialog.show();
        }
    }

    /**
     * 管理平台和业务平台需要提交经纬度
     *
     * @param latLng
     */
    private void requestAddress(LatLng latLng) {
        if (latLng == null) {
            return;
        }
        Call<BaseDTO> call = RequestHelper.getRequestApi().commitLngLat(latLng.longitude, latLng.latitude);
        call.enqueue(new Callback<BaseDTO>() {
            @Override
            public void onResponse(Call<BaseDTO> call, Response<BaseDTO> response) {
                Log.d(TAG, "onResponse:管理平台---> " + response.isSuccessful());
            }

            @Override
            public void onFailure(Call<BaseDTO> call, Throwable t) {
                Log.d(TAG, "onResponse: " + t);
            }
        });
        Call<BaseDTO> commitLngLat = HxTransmitRequestHelper.getRequestApi().commitLngLat(latLng.longitude, latLng.latitude);
        commitLngLat.enqueue(new Callback<BaseDTO>() {
            @Override
            public void onResponse(Call<BaseDTO> call, Response<BaseDTO> response) {
                Log.d(TAG, "onResponse:业务平台---> " + response.isSuccessful());
            }

            @Override
            public void onFailure(Call<BaseDTO> call, Throwable t) {

            }
        });

    }

    /**
     * 绑定到后台接收消息的service
     */
    private void bindToService() {
        //先启动service,避免app退出service即被杀死
        startService(new Intent(this, MessageService.class));
        Intent intent = new Intent(this, MessageService.class);
        bindService(intent, mServiceConnection, Context.BIND_AUTO_CREATE);
        mIsBind = true;
    }

    private ServiceConnection        mServiceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            mMessageService = ((MessageService.MyBinder) service).getService();
            //放在这里可以避免空指针异常
            mMessageService.connectAndSubscribe(UserManager.getClientId(), ContactManager.getTopics());
            mMessageService.addMessageReceiveListener(mListener);
            mMessageService.registerConnectLostListener(HomeActivity.this);
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            mMessageService.removeMessageReceiveListener(mListener);
            mMessageService.unregisterConnectionLostListener();
            mMessageService = null;
        }
    };
    /**
     * 收到消息的回调接口
     */
    private OnMessageReceiveListener mListener          = new OnMessageReceiveListener() {
        @Override
        public void receiveMessage(ChatMessage message) {
            Log.i("lwjing", "homeactivity " + message.toString());
            setUnReadCount();
            if (mWorkPagerFragment != null) {
                mWorkPagerFragment.receivedAnnoWarn();
            }

            //如果是系统消息，则只处理同意添加回复  群解散
            if (message.type == ChatMessageBody.Type.SYSTEM) {
                //被删除好友后需要刷新界面
                if (mMessageFragment == null) {
                    mMessageFragment = (MessageFragment) mFragmentManager.findFragmentByTag(
                            getResources().getString(R.string.main_tab_name_news));
                }
                mMessageFragment.initData();

                ChatSysMessageBody chatSysMessageBody = (ChatSysMessageBody) message.getMessageBody();
                String action = chatSysMessageBody.getAction();

                //被请求添加好友，不再重复更新最近联系人表
                if (ChatSysMessageBody.SysMessageType.ACTION_RQST_FED.equals(chatSysMessageBody.getAction())) {
                    return;
                }
                if (ChatSysMessageBody.SysMessageType.ACTION_RESP_FED.equals(action) && !"1".equals(chatSysMessageBody.getSystemMessageInfo()[2])) {
                    //非同意添加回复
                    return;
                }
                if (!ChatSysMessageBody.SysMessageType.ACTION_RESP_FED.equals(action)
                        && !ChatSysMessageBody.SysMessageType.ACTION_DESTROY_GROUP.equals(action)) {
                    return;
                }
                //本地没有群聊天记录，收到解散群消息，不做处理
                if (ChatSysMessageBody.SysMessageType.ACTION_DESTROY_GROUP.equals(action)) {
                    ChatMessage chatMessage = HistoryContactManager.getRecentMessageFromGroup(message.sender);
                    if (chatMessage == null) {
                        return;
                    }
                }
            }
            //更新常用联系人
            updateMessageStore(message);

            //messageFragment 刷新界面
            if (mMessageFragment != null) {
                mMessageFragment.initData();
            }
          /*  if(hxMessage!=null){
                //接受id
                ContactManager.getContactById( hxMessage.receiver);

            }*/
        }
    };

    private void updateMessageStore(ChatMessage message) {
        Contact mChatObject = ContactManager.getContactById(message.sender);
        if (mChatObject == null) {
            mChatObject = ContactManager.getGroupById(message.sender);
        }
        if (mChatObject == null) {
            mChatObject = ContactManager.getColleagueById(message.sender);
        }
        if (mChatObject == null) {
            //TODO
            Log.e("lwjing", "非好友非同事信息");
            return;
        }

        //只要进行了聊天界面就将聊会次数更新一次，添加到最近的联系人中
        if (mChatObject instanceof ContactGroup) {
            ContactStore.insert(mChatObject, 2, message.timestamp);
        } else if (mChatObject instanceof ContactPerson) {
            ContactStore.insert(mChatObject, 1, message.timestamp);
        }
        //显示在聊天记录页面中
        ContactStore.updateShow(mChatObject.getClientId(), 0);
        //更新聊天的次数
        ContactStore.updateChatCount(mChatObject.getClientId());
    }

    /**
     * 与后台接收消息的service解决绑定
     */
    private void unBindService() {
        if (mIsBind) {
            unbindService(mServiceConnection);
            mIsBind = false;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mMessageService == null) {
            return;
        }
        mMessageService.removeMessageReceiveListener(mListener);
        unBindService();
    }

    private void initTabs() {
        MainTab[] tabs = MainTab.values();
        int size = tabs.length;
        for (int i = 0; i < size; i++) {
            MainTab mainTab = tabs[i];
            TabHost.TabSpec tab = vTabHost.newTabSpec(getString(mainTab.getResName()));
            final View indicator;
            if (i == 1) {
                indicator = View.inflate(this, R.layout.tab_msg_indicator, null);
                msgCountTv = (TextView) indicator.findViewById(R.id.tv_count);
            } else {
                indicator = View.inflate(this, R.layout.tab_indicator, null);
            }

            TextView title = (TextView) indicator.findViewById(R.id.tab_title);
            ImageView icon = (ImageView) indicator.findViewById(R.id.iv_icon);
            Drawable drawable = this.getResources().getDrawable(mainTab.getResIcon());
            icon.setImageDrawable(i == 2 ? null : drawable);
            title.setText(getString(mainTab.getResName()));
            tab.setIndicator(indicator);

            if (i == 2 && StringUtils.isEmpty(Global.user.getOrgCode())) {
                vTabHost.addTab(tab, PromotionFragment.class, null);
            } else {
                vTabHost.addTab(tab, mainTab.getClz(), null);
                if (mWorkPagerFragment == null) {
                    mWorkPagerFragment = (WorkPagerFragment) mFragmentManager.findFragmentByTag(
                            getResources().getString(R.string.main_tab_name_work));
                }
            }
        }
        mMessageFragment = (MessageFragment) mFragmentManager.findFragmentByTag(
                getResources().getString(R.string.main_tab_name_news));
    }

    @Override
    protected void onResume() {
        super.onResume();
        setUnReadCount();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        boolean flags = false;
        if (vTabHost.getCurrentTab() == 0) {
            String currentTabTag = vTabHost.getCurrentTabTag();
            InfoPagerFragment infoPagerFragment = (InfoPagerFragment) mFragmentManager.findFragmentByTag(currentTabTag);
            flags = infoPagerFragment.onKeyDown();
        }
        if (flags) {
            return false;
        } else {
            return super.onKeyDown(keyCode, event);
        }
    }

    @Override
    public void onTabChanged(String tabId) {
        final int size = vTabHost.getTabWidget().getTabCount();
        for (int i = 0; i < size; i++) {
            View v = vTabHost.getTabWidget().getChildAt(i);
            if (i == vTabHost.getCurrentTab()) {
                v.setSelected(true);
                mTitle = mTitles[i];
            } else {
                v.setSelected(false);
            }
        }
        vWork.setSelected(vTabHost.getCurrentTab() == 2);
        if (mMessageFragment == null) {
            mMessageFragment = (MessageFragment) mFragmentManager.findFragmentByTag(
                    getResources().getString(R.string.main_tab_name_news));
        }
        if (!StringUtils.isEmpty(Global.user.getOrgCode())) {
            if (mWorkPagerFragment == null) {
                mWorkPagerFragment = (WorkPagerFragment) mFragmentManager.findFragmentByTag(
                        getResources().getString(R.string.main_tab_name_work));
            }
        }
    }

    /**
     * 在主界面中的tab上显示未读消息数
     */
    public void setUnReadCount() {
        int c = HistoryContactManager.getTotalUnreadCount();
        if (msgCountTv != null) {
            if (c > 0) {
                msgCountTv.setText("" + c);
                msgCountTv.setVisibility(View.VISIBLE);
            } else {
                msgCountTv.setVisibility(View.GONE);
            }
        }
    }

    @Override
    public void onBackPressed() {
        boolean isDoubleClick = PrefUtil.get(Constants.PK_DOUBLE_CLICK_EXIT, true);
        if (isDoubleClick) {
            long curTime = SystemClock.uptimeMillis();
            if ((curTime - mBackPressedTime) < (2 * 1000)) {
                AppManager.getAppManager().AppExit();
            } else {
                mBackPressedTime = curTime;
                Toast.makeText(this, "再次点击退出", Toast.LENGTH_LONG).show();
            }
        } else {
            AppManager.getAppManager().AppExit();
        }
    }

    private void userInfo() {
        if (TextUtils.isEmpty(Global.user.getServerAddress())) {
            return;
        }
        Call<UserInfoDTo> call = HxTransmitRequestHelper.getRequestApi().getUserInfo();
        autoClose(call);
        call.enqueue(new Callback<UserInfoDTo>() {
            @Override
            public void onResponse(Call<UserInfoDTo> call, Response<UserInfoDTo> response) {
                UserInfoDTo userInfoDTO = response.body();
                if (response.isSuccessful() && userInfoDTO != null) {
                    if (userInfoDTO.isSuccessful()) {
                        Global.userInfo = userInfoDTO.getData();
                    }
                } else {
                    ToastUtil.showToastShort(response.errorBody().toString());
                }
            }

            @Override
            public void onFailure(Call<UserInfoDTo> call, Throwable t) {
                Log.d(TAG, "onFailure: ----" + t);
                ToastUtil.showToastShort(t.getMessage());
            }
        });
    }

    /**
     * 在我的界面点击了退出回调
     */
    @Override
    public void onExit() {
        if (mMessageService == null) {
            return;
        }
        mMessageService.disConnect();
        mMessageService.stopSelf();
    }

    /**
     * mqtt连接丢失的回调，service中连接丢失了，
     * 在主界面弹出对话框
     */
    @Override
    public void connectionLost() {
        if (mSecureDialog != null && mSecureDialog.isShowing()) {
            return;
        }
        mSecureDialog = new AlertDialog.Builder(this)
                .setTitle(R.string.login_exception_title).setMessage(R.string.login_exception_content)
                .setNegativeButton(R.string.login_exception_exit, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        exit();
                    }
                }).setPositiveButton(R.string.login_exception_relogin, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        relogin();
                    }
                })
                .setCancelable(false)
                .create();
        mSecureDialog.setCanceledOnTouchOutside(false);
        mSecureDialog.show();
    }

    /**
     * 重新登录
     */
    public void relogin() {
        //如果设置了登出，则可能是想切换帐号,将自动登录取消
        PrefUtil.set(Constants.PK_AUTO_LOGIN, false);
        PrefUtil.set(Constants.PK_SAVE_PW, false);
        Intent intent = new Intent(this, LoginActivity.class);
        intent.putExtra("secure", 110);
        //携带安全信息到登录界面,如果登录界面不成功则要关闭activity栈中所有的activity
        //置空别名
        // JPushInterface.setAlias(this,0,null);
        JPushInterface.deleteAlias(this, 21027);
        startActivity(intent);
    }

    /**
     * 登录异常，退出登录，彻底杀死线程
     */
    public void exit() {
        //如果设置了登出，则可能是想切换帐号,将自动登录取消
        PrefUtil.set(Constants.PK_AUTO_LOGIN, false);
        PrefUtil.set(Constants.PK_SAVE_PW, false);
        if (mMessageService != null) {
            mMessageService.disConnect();
        }
        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.addCategory(Intent.CATEGORY_HOME);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
        backLoginConfig();
        android.os.Process.killProcess(android.os.Process.myPid());
    }

    private void backLoginConfig() {
        //清理缓存
        HxAppClearMgr.cleanApplicationData(getContext());
        HxTransmitRequestHelper.getBackLogin();
        // JPushInterface.setAlias(this,0,null);
        JPushInterface.deleteAlias(this, 21027);
    }
}


